import React, { Children, useState } from 'react';
import styles from './index.less';
import { useDebounceFn } from 'ahooks';
import { Select, Form, Button, DatePicker, ConfigProvider } from 'antd';
import zhCN from 'antd/es/locale/zh_CN';
import * as echarts from 'echarts';
import moment from 'moment';

import { HttpCode } from '#/utils/contacts.js';
import { Pointer, PageLoading, TRDefault } from '@/components/index.js';
import { fetchGetHistoryDayAheadPrice } from '@/pages/ETrade/MediumAndLongTermMarket/services.js';
import { pointConvert } from '@/pages/ETrade/MediumAndLongTermMarket/constant.js';

import BaseTable from '../BaseTable';
import { ChartHistoryBeforePrice } from '../Charts/index.js';
import { getAverageValueArr } from '../../index.jsx';

const { RangePicker } = DatePicker;
const dateFormat = 'YYYYMMDD';
let isFirst = true;

const HistoryBeforePrice = (props: any) => {
  const { provinceList, provinceId, marketList, date, remSize, point, unitId, marketId } = props;
  const [loading, setLoading] = useState(true),
    [historyDayAheadPrice, setHistoryDayAheadPrice] = useState<any>(),
    [unitList, setUnitList] = useState([]),
    [tableData, setTableData] = useState<any>([]),
    [tableHeader, setTableHeader] = useState<any>([]),
    [form] = Form.useForm();
  const onRegionChange = (val: any, opt: any) => {
    const list = opt?.children;
    setUnitList(list);
    if (!isFirst) {
      form.setFieldsValue({ unit: list[0].value, region: opt?.provinceId });
    }
    isFirst = false;
  };
  const defaultRequest = () => {
    isFirst = true;

    const opt = marketList.find((i: any) => i.value === marketId);
    onRegionChange(marketId, opt);
    form.submit();
  };
  React.useEffect(() => {
    defaultRequest();
  }, []);
  const getHistoryDayAheadPrice = async (values: any) => {
    setLoading(true);
    setTableData([]);
    const param = {
      provinceId: values.region,
      stationId: values.unit,
      timeOrder: values.point,
      startDate: moment(values.date[0]).format('YYYY-MM-DD'),
      endDate: moment(values.date[1]).format('YYYY-MM-DD'),
    };
    const res = await fetchGetHistoryDayAheadPrice(param);

    setLoading(false);
    if (res?.statusCode === HttpCode.SUCCESS) {
      const data = Object.entries(res.data || {});
      if (!data.length) return;
      const XAXIS: any = [];
      const _historyBeforePrice: any = [];
      data.forEach((t: any, i: number) => {
        t[1].map((_t: any, _i: number) => {
          if (i === 0) {
            XAXIS.push(pointConvert(_i + 1, parseInt(values.point)));
            _historyBeforePrice[_i] = [_t];
          } else {
            _historyBeforePrice[_i].push(_t);
          }
        });
      });
      const averageValue = getAverageValueArr(_historyBeforePrice);
      const _temp = echarts?.dataTool.prepareBoxplotData(_historyBeforePrice, {
        boundIQR: 'none',
      }).boxData;
      setHistoryDayAheadPrice({
        XAXIS,
        historyBeforePrice: _temp,
        averageValue,
      });
      const _tableData: any = [
        {
          title: '历史参考-最低',
        },
        {
          title: '历史参考-Q1',
        },
        {
          title: '历史参考-中位',
        },
        {
          title: '历史参考-Q3',
        },
        {
          title: '历史参考-最高',
        },
        {
          title: '历史参考-平均',
        },
      ];
      XAXIS.forEach((t: any, i: any) => {
        _tableData[0][t] = _temp[i][0];
        _tableData[1][t] = _temp[i][1];
        _tableData[2][t] = _temp[i][2];
        _tableData[3][t] = _temp[i][3];
        _tableData[4][t] = _temp[i][4];
        _tableData[5][t] = averageValue[i];
      });
      setTableData(_tableData);
      setTableHeader(
        XAXIS.map((t: any) => ({
          name: t,
          field: t,
        })),
      );
    }
  };
  const _onFinish = useDebounceFn(
    (values: any) => {
      getHistoryDayAheadPrice(values);
    },
    { wait: 500 },
  );
  const initialValues = () => ({
    market: marketId,
    region: provinceId,
    unit: unitId,
    point: point,
    date: date,
  });
  const _onReset = useDebounceFn(
    () => {
      form.resetFields();
      defaultRequest();
    },
    { wait: 500 },
  );
  return (
    <ConfigProvider locale={zhCN}>
      <div className={styles.container}>
        <div className={styles.header}>
          <Form
            form={form}
            initialValues={initialValues()}
            className={styles.formStyles}
            onFinish={_onFinish.run}
          >
            <Form.Item
              name="market"
              className={styles.cell_item}
              rules={[{ required: true, message: '请选择省份' }]}
            >
              <Select
                style={{ width: 200 }}
                placeholder="选择省份"
                showSearch
                options={marketList}
                onChange={(e: any, { provinceId }: any) => {
                  form.setFieldsValue({ region: provinceId });
                }}
                filterOption={(input, option) => {
                  return (option?.label as unknown as string)
                    .toLowerCase()
                    .includes(input.toLowerCase());
                }}
              />
            </Form.Item>
            <Form.Item noStyle name="region" />
            <Form.Item
              name="unit"
              className={styles.cell_item}
              rules={[{ required: true, message: '请选择交易单元' }]}
            >
              <Select
                showSearch={true}
                style={{ width: 200 }}
                placeholder="请选择交易单元"
                options={unitList}
                filterOption={(input, option) => {
                  return (option?.label as unknown as string)
                    .toLowerCase()
                    .includes(input.toLowerCase());
                }}
              />
            </Form.Item>
            <Form.Item name="point" className={styles.cell_item}>
              <Pointer
                className={styles.font}
                data={point}
                onChange={(e: any) => {
                  form.setFieldsValue({ point: e.target.value });
                }}
              />
            </Form.Item>
            <Form.Item
              name="date"
              className={styles.cell_item}
              rules={[{ required: true, message: '请选择日期' }]}
            >
              <RangePicker
                className={styles.font}
                style={{ width: 260 }}
                format={dateFormat}
                separator={'-'}
              />
            </Form.Item>
            <Button className={styles.submit} type="primary" htmlType="submit">
              查询
            </Button>
            <Button className={styles.reset} htmlType="reset" onClick={_onReset.run} ghost>
              重置
            </Button>
          </Form>
        </div>
        {loading ? (
          <PageLoading />
        ) : (
          <div className={styles.content}>
            {tableData?.length ? (
              <>
                <div style={{ flex: 1 }}>
                  <ChartHistoryBeforePrice data={historyDayAheadPrice} scale={remSize / 100} />
                </div>
                <div style={{ marginTop: 28, overflow: 'hidden' }}>
                  <BaseTable tableData={tableData} tableHeader={tableHeader} />
                </div>
              </>
            ) : (
              <TRDefault type="emptysm" />
            )}
          </div>
        )}
      </div>
    </ConfigProvider>
  );
};

export default HistoryBeforePrice;
